package com.idol.web.container;

import com.idol.web.servlet.http.HttpServlet;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Supreme_Sir
 * @version 1.0
 * @className container
 * @description Servlet 容器
 * @date 2020/11/22 20:05
 **/
public class ServletContainer {
    private static ServletContainer instance = new ServletContainer();
    private Map<String, Map<String, HttpServlet>> webProjectContainer;

    /**
     * 检查是否包含指定名称是 Servlet
     * @param webSite 网站名称
     * @param url 资源路径
     */
    public boolean containsKey(String webSite, String url) {
        if (webProjectContainer.containsKey(webSite) && webProjectContainer.get(webSite).containsKey(url)) {
            return true;
        }
        return false;
    }

    /**
     * 获取指定的 Servlet
     * @param webSite 网站名称
     * @param url 资源路径
     */
    public HttpServlet get(String webSite, String url) {
        Map<String, HttpServlet> webSiteMap = webProjectContainer.get(webSite);
        if (null == webSiteMap) {
            return null;
        } else {
            return webSiteMap.get(url);
        }
    }

    /**
     * 将 Servlet 放入 web 容器
     * @param webSite 网站名称
     * @param url 资源路径
     * @param servlet 被放入容器的 Servlet
     */
    public void put(String webSite, String url, HttpServlet servlet) {
        Map<String, HttpServlet> webSiteMap = webProjectContainer.get(webSite);
        if (null != webSiteMap) {
            webSiteMap.put(url, servlet);
        } else {
            webSiteMap = new HashMap<>(16);
            webSiteMap.put(url, servlet);
            webProjectContainer.put(webSite, webSiteMap);
        }
    }

    /**
     * 获取 ServletContainer 实例
     */
    public static ServletContainer getInstance() {
        return instance;
    }

    private ServletContainer() {
        webProjectContainer = new HashMap<>(16);
    }
}
